package org.dawfinn.droiditarian;

import org.dawfinn.droiditarian.data.Deed;
import org.dawfinn.droiditarian.data.DeedsDBAdapter;
import org.dawfinn.droiditarian.data.Deed.OnDeedChangeListener;
import org.dawfinn.droiditarian.listener.CompletedAdapter;
import org.dawfinn.droiditarian.listener.CompletedStatusListener;
import org.dawfinn.droiditarian.listener.FavoriteStatusListener;
import org.dawfinn.droiditarian.view.CompletedCheck;
import org.dawfinn.droiditarian.view.FavoriteStar;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ExpandedDeed extends Activity implements OnClickListener, OnMenuItemClickListener, OnDeedChangeListener {

	public static final int CAMERA_RESULT = 0;
	private static final int CONTEXT_MENU = 0;
	private static final int FAVORITE_MENU_ITEM = 0;
	private static final int COMPLETE_MENU_ITEM = 1;
	private static final int COMPLETE_ATTACH_MENU_ITEM = 2;
	private static final int EMAIL_MENU_ITEM = 3;
	private static final String EMPTY = "";
	private static final String DEED_KEY = "deedKey";

	private Deed deed;

	// View components
	private Button favoriteButton;
	private Button completedButton;
	private Button completedAttachButton;
	private Button emailButton;
	private LinearLayout controls;
	private LinearLayout lowerControls;
	private CompletedCheck completedBox;
	private FavoriteStar favoriteBox;

	private AnimationSet slideDown;

	// Listener component
	private CompletedAdapter completedAdapter;

	@Override
	public void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		this.setContentView(R.layout.deed_expanded);
		int deedKey = getIntent().getIntExtra(DEED_KEY, -1);
		this.deed = getDeedFromId(deedKey);
		deed.setOnDeedChangeListener(this);
		initLayout();
		setListeners();
	}

	private Deed getDeedFromId(int deedKey) {
		DeedsDBAdapter db = new DeedsDBAdapter(this);
		db.open();
		Deed deed = db.getDeed(deedKey);
		db.close();
		return deed;
	}

	private void initLayout() {
		((TextView) findViewById(R.id.name)).setText(deed.getName());

		((TextView) findViewById(R.id.description)).setText(deed.getDescription());

		((TextView) findViewById(R.id.explanation)).setText(deed.getExplanation());

		TextView moreInfo = (TextView) findViewById(R.id.info);
		TextView moreInfoTitle = (TextView) findViewById(R.id.more_info_title);
		if (deed.getMoreInfo().trim().equals(EMPTY)) {
			moreInfo.setVisibility(View.GONE);
			moreInfoTitle.setVisibility(View.GONE);
		} else {
			moreInfo.setText(deed.getMoreInfo());
			Linkify.addLinks(moreInfo, Linkify.ALL);
		}

		favoriteBox = (FavoriteStar) findViewById(R.id.favoriteStar);
		favoriteBox.setUseAnimations(true);
		favoriteButton = (Button) findViewById(R.id.favorite);
		setFavoriteWidgets();
		completedBox = (CompletedCheck) findViewById(R.id.completedCheck);
		completedBox.setUseAnimations(true);
		completedButton = (Button) findViewById(R.id.completed);
		completedAttachButton = (Button) findViewById(R.id.completedAttach);
		initCompletedWidgets();
		emailButton = (Button) findViewById(R.id.email);
		controls = (LinearLayout) findViewById(R.id.deedControlsOuter);
		lowerControls = (LinearLayout) findViewById(R.id.deedControlsLower);

		slideDown = (AnimationSet) AnimationUtils.loadAnimation(this, R.anim.slide_down);
		slideDown.setAnimationListener(new HideViewListener(lowerControls));
	}

	private void setFavoriteWidgets() {
		favoriteBox.setChecked(deed.isFavorite());
		favoriteButton.setText(deed.isFavorite() ? getString(R.string.unfavorite_menu_item) : getString(R.string.favorite_menu_item));
	}

	private void initCompletedWidgets() {
		completedBox.setChecked(deed.isCompleted());

		int visibility = deed.isCompleted() ? View.GONE : View.VISIBLE;
		completedButton.setVisibility(visibility);
		completedAttachButton.setVisibility(visibility);

	}

	private void updateCompletedWidgets() {
		completedBox.setChecked(deed.isCompleted());

		if (deed.isCompleted()) {
			if (lowerControls.getVisibility() != View.GONE)
				controls.startAnimation(slideDown);
		} else {
			lowerControls.setVisibility(View.VISIBLE);
		}
	}

	private void setListeners() {
		favoriteButton.setOnClickListener(new FavoriteStatusListener(deed, this));
		completedButton.setOnClickListener(new CompletedStatusListener(deed, this));

		completedAttachButton.setOnClickListener(this);

		// Set up the adapter that will send the location and completed
		// status if the completed attach box is checked
		completedAdapter = new CompletedAdapter(deed, this);

		emailButton.setOnClickListener(new EmailListener());
	}

	public boolean onMenuItemClick(MenuItem arg0) {
		doCompleteAttach();
		return true;
	}

	public void onClick(View arg0) {
		doCompleteAttach(); 
	}

	private void doCompleteAttach() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(intent, ExpandedDeed.CAMERA_RESULT);
	}

	/**
	 * After picture is taken this will get called.
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_RESULT) {
			if (resultCode != Activity.RESULT_CANCELED) {
				completedAdapter.saveDeedState();

				// requery
				deed = getDeedFromId(deed.getId());
				completedAdapter.uploadCompleteToServer();
				completedAdapter.uploadLocationToServer((Bitmap) data.getExtras().get("data"));
				updateCompletedWidgets();
			}
		}
	}

	private class EmailListener implements OnClickListener, OnMenuItemClickListener {

		public void onClick(View arg0) {
			doEmail();
		}

		public boolean onMenuItemClick(MenuItem arg0) {
			doEmail();
			return true;
		}

		private void doEmail() {
			/* Create the Intent */
			final Intent emailIntent = new Intent(Intent.ACTION_SEND);

			/* Fill it with Data */
			emailIntent.setType("plain/text");
			emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_title));
			// If there isn't more info, then the more info text should just be blank.
			// Otherwise, it should be the more info paragraph
			String moreInfoText = deed.getMoreInfo();
			String emailMoreInfoText = (moreInfoText.trim().equals("")) ? ""
					: String.format(getString(R.string.email_more_info), moreInfoText);
			// The email body string has placeholders for: 1) deed name 2)
			// description 3) explanation 4) more info
			emailIntent.putExtra(Intent.EXTRA_TEXT, String.format(getString(R.string.email_body), deed.getName(), deed.getDescription(), deed
			        .getExplanation(), emailMoreInfoText));

			/* Send it off to the Activity-Chooser */
			startActivity(Intent.createChooser(emailIntent, getString(R.string.email_intent_title)));
		}
	}

	public void onDeedChanged(Deed deed) {
		this.deed = deed;
		setFavoriteWidgets();
		updateCompletedWidgets();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.getItem(COMPLETE_MENU_ITEM).setVisible(!deed.isCompleted());
		menu.getItem(COMPLETE_ATTACH_MENU_ITEM).setVisible(!deed.isCompleted());
		int favText = deed.isFavorite() ? R.string.unfavorite_menu_item : R.string.favorite_menu_item;
		menu.getItem(FAVORITE_MENU_ITEM).setTitle(getString(favText));
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuItem favorite = menu.add(CONTEXT_MENU, FAVORITE_MENU_ITEM, Menu.NONE, R.string.favorite_menu_item);
		favorite.setOnMenuItemClickListener(new FavoriteStatusListener(deed, this));
		MenuItem complete = menu.add(CONTEXT_MENU, COMPLETE_MENU_ITEM, Menu.NONE, R.string.complete_menu_item);
		complete.setOnMenuItemClickListener(new CompletedStatusListener(deed, this));
		MenuItem completeAttach = menu.add(CONTEXT_MENU, COMPLETE_ATTACH_MENU_ITEM, Menu.NONE, R.string.complete_attach_menu_item);
		completeAttach.setOnMenuItemClickListener(this);
		MenuItem email = menu.add(CONTEXT_MENU, EMAIL_MENU_ITEM, Menu.NONE, R.string.email_menu_item);
		email.setOnMenuItemClickListener(new EmailListener());
		return true;
	}
}
